package org.gp953.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取请求头中的token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)){// token不为空才用token作为键去redis中取值
            // 通过token去redis中获取数据
            Object loginInfoto = redisTemplate.opsForValue().get(token);
            if (loginInfoto != null){// loginDto不为空则说明token存在，应该重置有效时间为30分钟，并放行
                // 重置token有效时间为30分钟
                redisTemplate.opsForValue().set(token,loginInfoto,30, TimeUnit.MINUTES);
                // 如果要做权限校验应该写在这里
                return true;
            }

        }
        // 不能获取token则是没登录应该拦截，要给前端返回一个Json类型的结果
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }

}
